package lxmysql

import (
	"gitee.com/lxgow/lxconv"
	lconv "github.com/lixu-any/go-tools/conv"
)

// HashCode 计算 SQL 语句的哈希码
func HashCode(sql string, args []interface{}) int {
	hash := 17
	hash = hash*31 + len(sql)
	for _, arg := range args {
		hash = hash*31 + HashCodeOfArg(arg)
	}
	return hash
}

// HashCodeOfArg 计算参数的哈希码
func HashCodeOfArg(arg interface{}) int {
	switch v := arg.(type) {
	case int:
		return v
	case int8:
		return int(v)
	case int16:
		return int(v)
	case int32:
		return int(v)
	case int64:
		return int(v)
	case uint:
		return int(v)
	case uint8:
		return int(v)
	case uint16:
		return int(v)
	case uint32:
		return int(v)
	case uint64:
		return int(v)
	case float32:
		return int(v)
	case float64:
		return int(v)
	case string:
		return len(v)
	default:
		return 0
	}
}

// GenCacheKey 生成缓存名字
func GenCacheKey(sql string, args []interface{}) string {
	return lxconv.EncryMD5(sql + lconv.JsonEncode(args))
}
